import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/notice_v2_entity.dart';

import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class NoticeEditLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  final noticeInfo = NoticeV2Entity().obs;
  final isCreate = false.obs;
  final ifShowOwnerPhone = false.obs;
  final shareType = 2.obs;

  var attachmentNames = [].obs;
  final List<PlatformFile> _paths = [];

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController titleController = TextEditingController();
  final TextEditingController subjectAmountController = TextEditingController();
  final TextEditingController servicePriceController = TextEditingController();
  final TextEditingController cooperRatioController = TextEditingController();
  final TextEditingController contentController = TextEditingController();

  final Map<int, String> shareTypeMap = {
    1: '机构内部',
    2: '跨机构公开',
  };

  @override
  void onInit() {
    super.onInit();

    NoticeEditParams params = Get.arguments;

    isCreate.value = params.isCreate;
    if (!isCreate.value) {
      noticeInfo.value = params.noticeInfo!;
    } else {
      noticeInfo.value.attaches = [];
    }
  }

  void setShowOwnerPhone(bool value) {
    ifShowOwnerPhone.value = value;
  }

  void setShareType(int value) {
    shareType.value = value;
  }

  // 选择文件
  void pickFile() async {
    var files = (await FilePicker.platform.pickFiles(
      type: FileType.any,
      allowMultiple: true,
    ))
        ?.files;

    if (files != null && files.isNotEmpty) {
      _paths.addAll(files);
      attachmentNames.addAll(files.map((e) => e.name).toList());
    }
  }

  // 删除文件
  void deleteFile(int index) {
    _paths.removeAt(index);
    attachmentNames.removeAt(index);
  }

  void onSubmitted() async {
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();

      EasyLoading.show(status: '正在提交...');
      final result = await _uploadFiles();

      if (!result) {
        EasyLoading.dismiss();
        EasyLoading.showError('上传文件失败');
        return;
      }

      _createNotice();
    }
  }

  Future<bool> _uploadFiles() async {
    if (_paths.isEmpty) {
      return true;
    }

    for (var path in _paths) {
      final result = await apiService.uploadFile(path.path!);
      if (result != null) {
        noticeInfo.value.attaches!
            .add(NoticeV2Attaches(name: result.name, url: result.tempPath));
      } else {
        return false;
      }
    }

    return true;
  }

  void _createNotice() async {
    final result = await apiService.editNotice(
      commonService.getRole(),
      contentController.text,
      shareType.value,
      phoneController.text,
      subjectAmountController.text,
      servicePriceController.text,
      title: titleController.text,
      ownerContact: ifShowOwnerPhone.value ? 1 : 0,
      cooperRatio: cooperRatioController.text.isEmpty
          ? 0
          : int.parse(cooperRatioController.text),
      attaches: noticeInfo.value.attaches ?? [],
    );

    if (result != null) {
      EasyLoading.dismiss();
      EasyLoading.showSuccess('提交成功');
      Get.back(result: true);
    } else {
      EasyLoading.dismiss();
      EasyLoading.showError('提交失败');
    }
  }
}

class NoticeEditParams {
  bool isCreate = false;
  NoticeV2Entity? noticeInfo;

  NoticeEditParams({this.isCreate = false, this.noticeInfo});
}

class NoticeFileInfo {
  String name;
  String url;

  NoticeFileInfo(this.name, this.url);
}
